﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace N2.ComponentModel
{
	using Details;

	public class DetailCollectionDictionaryEditor : ContentCollectionEditor
	{
		#region Constructors

		public DetailCollectionDictionaryEditor(Type type) : base(type) { }

		#endregion Constructors

		protected override Type CreateCollectionItemType()
		{
			return typeof(DetailCollection);
		}

		protected override Type[] CreateNewItemTypes()
		{
			return new[] { typeof(DetailCollection), };
		}

		protected override object[] GetItems(object editValue)
		{
			var _dictionary = editValue as IDictionary<string, DetailCollection>;
			return
				null == _dictionary
					? new object[0]
					: (from _collection in _dictionary
					   select _collection.Value)
					   .Cast<object>()
					   .ToArray();
		}

		protected override object SetItems(object editValue, object[] value)
		{
			var _dictionary = editValue as IDictionary<string, DetailCollection>;

			foreach (var _item in value.Cast<DetailCollection>()) {
				if (_dictionary.ContainsKey(_item.Name)) {
					_dictionary[_item.Name] = _item;
				} else {
					_dictionary.Add(_item.Name, _item);
				}
			}

			return _dictionary;
		}

	}
}
